import type { StudentWordItem, StudentWordListRequestParams, StudentWordReviewContent, StudentWordShorthandStudyWordItem } from '@/api/types/student'
import { handleApiError, studentApi } from '@/api'
import { RecentStage } from '@/enums/course'
import { useStudentUnitStore } from '@/stores/modules/useStudentUnitStore'
import { formatDate } from '@/utils/format'
import { message } from '@/utils/message'
import { navigateBack, navigateTo } from '@/utils/navigation'
import { defineStore } from 'pinia'
import { useCurrentStudentInfoStore } from './useCurrentStudentInfoStore'

const studentInfoStore = useCurrentStudentInfoStore()
export interface UnitStudyGroup {
  words: StudentWordItem[]
}

export const useUnitStudyWordsStore = defineStore(
  'unitStudyWords',
  {
    state: () => {
      return {
        groups: [] as UnitStudyGroup[],
        studyWords: [] as StudentWordShorthandStudyWordItem[],

        // 学习的请求参数
        commonRequestParams: {
          studentId: 0,
          lessonId: 0,
          courseId: 0,
          unitNo: 0,
          studyRecordId: 0,
          startTime: '',
          endTime: '',
        },

        // 单词识别, review
        entryName: 'shorthand',

        // 当前分组
        currentGroupIndex: 0,

        currentWordIndex: 0,
        // 存储混合检查的组索引
        mixedGroups: [] as number[],
        // 当前学习状态
        currentLearningState: 'wordMemory',
      }
    },
    getters: {
      isReviewEntry: (state) => {
        return state.entryName === 'review'
      },
      currentGroup: (state) => {
        return state.groups[state.currentGroupIndex] || []
      },
      totalGroups: (state) => {
        return state.groups.length
      },
      isLastGroup: (state) => {
        return state.currentGroupIndex === state.groups.length - 1
      },
      allGroupWords: (state) => {
        return state.groups.flatMap(group => group.words)
      },
      // 根据当前状态和混合组获取单词
      groupWords: (state) => {
        // 如果有混合组，返回混合组的单词
        if (state.mixedGroups.length > 0) {
          return state.mixedGroups.flatMap(groupIndex =>
            state.groups[groupIndex]?.words || [],
          )
        }
        // 否则返回当前组的单词
        return state.groups[state.currentGroupIndex]?.words || []
      },
      // 混合组标题
      mixedGroupTitle: (state) => {
        if (state.mixedGroups.length === 0) {
          return '混合检查'
        }
        // 将0-based索引转换为1-based显示
        const groupNumbers = state.mixedGroups.map(index => index + 1)
        return `混合检查 ${groupNumbers.join('、')}组`
      },
    },
    actions: {
      switchToReview() {
        this.entryName = 'review'
      },
      // 切换到单词识别
      switchToShorthand() {
        this.entryName = 'shorthand'
      },
      updateStudyWords(words: StudentWordShorthandStudyWordItem[]) {
        this.studyWords = words
      },
      resetStudyWords() {
        this.studyWords = []
      },
      updateStudyStartTime(startTime?: string) {
        this.commonRequestParams.startTime = startTime || formatDate(new Date())
      },
      updateUnitNo(unitNo: number) {
        this.commonRequestParams.unitNo = unitNo
      },

      updateWordGroups(data: StudentWordReviewContent) {
        this.commonRequestParams.courseId = data.courseId
        this.commonRequestParams.studentId = data.studentId
        this.commonRequestParams.unitNo = data.unitNo
        this.commonRequestParams.studyRecordId = data.studyRecordId

        this.currentGroupIndex = data.currentGroupNo
        this.groups = data.groups
        // this.groups = formatGroups(data.groups, data.currentGroupNo)
        // this.currentGroupIndex = 0
        console.log(this.groups, 'this.groups', this.currentGroupIndex)

        this.mixedGroups = []
        this.currentLearningState = 'wordMemory'
      },
      incrementCurrentGroupIndex() {
        this.currentGroupIndex += 1
      },
      decrementCurrentGroupIndex() {
        this.currentGroupIndex -= 1
      },
      setCurrentGroupIndex(index: number) {
        this.currentGroupIndex = index
      },
      setMixedGroups(groupIndexes: number[]) {
        this.mixedGroups = groupIndexes
      },
      setCurrentLearningState(state: string) {
        this.currentLearningState = state
      },
      // 清除混合组
      clearMixedGroups() {
        this.mixedGroups = []
      },

      // 是否生进入学前检测
      async startPreCheckStudy(params: StudentWordListRequestParams) {
        const [error, data] = await studentApi.getUnitStage(params)
        if (error) {
          return handleApiError(error)
        }

        const { wordStudyInfo } = data.data
        if (wordStudyInfo.recentStage === RecentStage.FINISHED) {
          return message.info('已经学完 ， 能能再学习了！')
        }

        // 是否体验课
        const isExperienceCourse = useStudentUnitStore().isExperienceCourse

        // 如果学前检查阶段进入学前检查
        if (wordStudyInfo.recentStage === RecentStage.PRE_CHECK) {
          navigateTo({
            url: '/pages/wordStudy/preCheck',
            params: {
              ...params,
              isExperienceCourse,
            },
          })
          return
        }

        this.startStudyWords(params)
      },

      async startStudyAfterCheck(params: StudentWordListRequestParams) {
        const [error, data] = await studentApi.shorthandGetStudyContent({
          studentId: params.studentId,
          courseId: params.courseId,
          unitNo: params.unitNo,
          lessonId: studentInfoStore.lessonId,
        })

        if (error) {
          handleApiError(error)
          return null
        }
        // 更新单词分组
        this.updateWordGroups(data.data)

        navigateTo({
          url: '/pages/wordStudy/afterCheck',
        })
      },

      async startStudyWords(params: StudentWordListRequestParams) {
        const apiCallback = this.isReviewEntry ? studentApi.getReviewStudyContent : studentApi.shorthandGetStudyContent

        const [error, data] = await apiCallback({
          studentId: params.studentId,
          courseId: params.courseId,
          unitNo: params.unitNo,
          lessonId: studentInfoStore.lessonId,
        })

        if (error) {
          handleApiError(error)
          return null
        }
        // 更新单词分组
        this.updateWordGroups(data.data)

        // TODO 到时候根据真实的接口判断
        if (data.data.groups.length === 0) {
          message.info('没有下一单元了')
          setTimeout(() => {
            navigateBack()
          }, 200)
          return
        }

        // 跳转识记页面
        navigateTo({
          url: '/pages/wordStudy/wordMemory',
          params,
        })

        return data
      },
    },
    persist: true,
  },
)
